//
//  DiscoveryInfoController.m
//  collection
//
//  Created by 靖 张 on 11/26/11.
//  Copyright (c) 2011 Tsinghua University. All rights reserved.
//

#import "DiscoveryInfoController.h"
#import "CollectionDataManager.h"
#import "FeedDetailController.h"
#import "AppDelegate.h"

#define NUMBER_OF_COLUMNS 3

@interface DiscoveryInfoController()

@property (nonatomic, retain)   WaterflowView*  flowView;
@property (nonatomic, retain)   NSMutableDictionary* pair;
@property (nonatomic) int currentPage;

- (void)onTapImage:(UIGestureRecognizer*)gestureRecognizer;
- (BOOL)addNewImage;

@end

@implementation DiscoveryInfoController

@synthesize homepageRootController = _homepageRootController;
@synthesize flowView = _flowView;
@synthesize pair = _pair;
@synthesize currentPage = _currentPage;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title  = @"发现";
        
        NSMutableDictionary* dic = [[NSMutableDictionary alloc] initWithCapacity:1];
        self.pair = dic;
        [dic release];
    }
    
    return self;
}

- (void)dealloc {
    self.homepageRootController = nil;
    self.flowView = nil;
    self.pair = nil;
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"all_bg"]];
    
    CGRect frame = self.view.frame;
    frame.size.height -= 88;
    WaterflowView* flowView = [[WaterflowView alloc] initWithFrame:frame];
    flowView.flowdatasource = self;
    flowView.flowdelegate = self;
    self.flowView = flowView;
    [flowView release];
    [self.view addSubview:self.flowView];
    
    self.currentPage = 1;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - [UIScrollViewDelegate]

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
}

#pragma mark - [WaterflowDataSource]

- (NSInteger)numberOfColumnsInFlowView:(WaterflowView *)flowView {
    
    return NUMBER_OF_COLUMNS;
}

- (NSInteger)flowView:(WaterflowView *)flowView numberOfRowsInColumn:(NSInteger)column {
    
    return 8;
}

- (WaterFlowCell*)flowView:(WaterflowView *)flowView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
	WaterFlowCell *cell = [self.flowView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if(cell == nil)
	{
		cell  = [[[WaterFlowCell alloc] initWithReuseIdentifier:CellIdentifier] autorelease];
	}
	
	float height = [self flowView:nil heightForRowAtIndexPath:indexPath];
    CGRect frame = CGRectMake(0, 0, 100, height);
    
    frame.origin.y += 5;
    frame.size.height -= 5;
    cell.imageView.frame = frame;
    
    frame.size.height += 5;
    cell.transparentView.frame = frame;
    int index = (indexPath.row + indexPath.section )  % 8;
	NSString* picFileName = [NSString stringWithFormat:@"pic_%d", index + 1];
    cell.imageView.image = [UIImage imageNamed:picFileName];
    
	return cell;
}

#pragma mark - [WaterflowDelegate]

- (CGFloat)flowView:(WaterflowView *)flowView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    float height = 0;
	switch ((indexPath.row + indexPath.section)  % 8) {
		case 0:
			height = 87;
			break;
		case 1:
			height = 87;
			break;
		case 2:
			height = 87;
			break;
		case 3:
			height = 165;
			break;
		case 4:
			height = 110;
			break;
		case 5:
			height = 143;
			break;
        case 6:
            height = 140;
            break;
        case 7:
            height = 100;
            break;
		default:
			break;
	}
	
    height += 5;
//	height += indexPath.row;// + indexPath.section;
	
	return height;
}

- (void)flowView:(WaterflowView *)flowView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Select at %@", indexPath);
    
    int randomIndex = indexPath.row % 8 + 1;
    long long feedID = (randomIndex <= 4) ? 10001 : 10004;
//    int feedID = [[self.pair objectForKey:num] intValue];
    int index = (indexPath.section + indexPath.row) % 8;
    if (index < 4) {
        feedID = 10001;
    }
    else {
        feedID = 10004;
    }
    
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    NSArray* feedList = sharedDataManager.feedList;
    
    Feed* theFeed = nil;
    for (Feed* feed in feedList) {
        if (feed.feedID == feedID) {
            theFeed = feed;
            break;
        }
    }
    
    if (theFeed == nil) {
        return;
    }
    
    FeedDetailController* feedDetailController = [[FeedDetailController alloc] initWithNibName:@"FeedDetailController" bundle:nil];
    feedDetailController.feed = theFeed;
    feedDetailController.focusPicName = [NSString stringWithFormat:@"pic_%d", index + 1];
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.rootNavigationController pushViewController:feedDetailController animated:YES];
    [feedDetailController release];
}

- (void)flowView:(WaterflowView *)flowView didSelectAtCell:(WaterFlowCell *)cell ForIndex:(int)index
{
    
}

- (void)flowView:(WaterflowView *)_flowView willLoadData:(int)page
{
    [self.flowView reloadData];
}

#pragma mark - [Private methods]

- (BOOL)addNewImage {
    
    static int tag = 10;
    int picNum = 8;
    
    int randomIndex = arc4random() % picNum + 1;
    NSString* picName = [NSString stringWithFormat:@"pic_%d", randomIndex];
    UIImage* img = [UIImage imageNamed:picName];
    
    CGSize size = CGSizeMake(100, img.size.height * 100 / img.size.width);
    UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    
    imgView.tag = tag++;
    long long feedID = (randomIndex <= 4) ? 10001 : 10004;
    [self.pair setObject:[NSNumber numberWithLong:feedID] forKey:[NSNumber numberWithInt:imgView.tag]];
    
    imgView.userInteractionEnabled = YES;
    UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapImage:)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [imgView addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];
    
    imgView.image = img;
    
    return YES;
}

- (void)onTapImage:(UIGestureRecognizer *)gestureRecognizer {
    
    UIView* view = gestureRecognizer.view;
    NSNumber* num = [NSNumber numberWithInt:view.tag];
    
    int feedID = [[self.pair objectForKey:num] intValue];
    
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    NSArray* feedList = sharedDataManager.feedList;
    
    Feed* theFeed = nil;
    for (Feed* feed in feedList) {
        if (feed.feedID == feedID) {
            theFeed = feed;
            break;
        }
    }
    
    if (theFeed == nil) {
        return;
    }
    
    FeedDetailController* feedDetailController = [[FeedDetailController alloc] initWithNibName:@"FeedDetailController" bundle:nil];
    feedDetailController.feed = theFeed;
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.rootNavigationController pushViewController:feedDetailController animated:YES];
    [feedDetailController release];
}

@end
